<?php
namespace app\store\controller;
use app\store\model\Order as OrderModel;
use app\store\model\ShopClerk as ShopClerkModel;
use app\store\model\Shop as ShopModel;

/**
 * 订单管理
 */
class Order extends Controller
{
	
	
	/**
     * 全部退款订单列表
     */
    public function refund_list($search='')
    {
        return $this->getList('全部退款订单列表','refund',$search);
    }
	
	/**
     * 待退款订单列表
     */
    public function refund10_list($search='')
    {
        return $this->getList('待退款订单列表','refund10',$search);
    }
	
	/**
     * 已退款订单列表
     */
    public function refund20_list($search='')
    {
        return $this->getList('已退款订单列表','refund20',$search);
    }

    /**
     * 待收款订单列表
     */
    public function collection_list($search='')
    {
        return $this->getList('待收款订单列表','collection',$search);
    }

    /**
     * 待接单订单列表
     */
    public function shop_list($search='')
    {
        return $this->getList('待接单订单列表','shop',$search);
    }
	
    /**
     * 待发货订单列表
     */
    public function delivery_list($search='')
    {
        return $this->getList('待发货订单列表','delivery',$search);
    }

    /**
     * 待收货订单列表
     */
    public function receipt_list($search='')
    {
        return $this->getList('待收货订单列表','receipt',$search);
    }

    /**
     * 已完成订单列表
     */
    public function complete_list($search='')
    {
        return $this->getList('已完成订单列表','complete',$search);
    }

    /**
     * 被取消订单列表
     */
    public function cancel_list($search='')
    {
        return $this->getList('被取消订单列表','cancel',$search);
    }

    /**
     * 全部订单列表
     */
    public function all_list($search='')
    {
        return $this->getList('全部订单列表','all',$search);
    }

    /**
     * 订单列表
     */
    private function getList($title,$dataType, $search='')
    {   
        $shop_id = '';
        if(!$this->is_admin OR $this->shop_mode == 10){
           $shop_id = $this->shop_id;
        }
        $model = new OrderModel;
        $list = $model->getList($dataType,$shop_id,'',$search);
        return $this->fetch('index', compact('title','list'));
    }

    /**
     * 订单详情
     */
    public function detail($order_id)
    {
        $detail = OrderModel::detail($order_id);
		$model = new ShopClerkModel;
		$clerk = $model->getLists($detail['shop_id'],30);
        return $this->fetch('detail', compact('detail','clerk'));
    }

    /**
     * 确认接单
     */
    public function shop($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->setShopStatus()) {
            return $this->renderSuccess('操作完成');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 设置外卖配送状态
     */
    public function deliveryStatus($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->setDeliveryStatus($this->postData('delivery'))) {
            return $this->renderSuccess('操作完成');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 确认发货
     */
    public function delivery($order_id)
    {
        $model = OrderModel::detail($order_id);
        $delivery = $this->postData('delivery');
        if($delivery['company']==10 AND isset($delivery['shop_clerk_id'])){
            $delivery['delivery_status'] = 20;
            if ($model->setDeliveryStatus($delivery)) {
                return $this->renderSuccess('操作成功');
            }
            return $this->renderError('操作失败');
        }
        if ($model->setDelivery($delivery['company'])) {
            return $this->renderSuccess('操作完成');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }
	
	/**
     * 退款操作
     */
    public function refund($order_id)
    {
        $refund = $this->postData('refund');
        $model = OrderModel::detail($order_id);
        if ($model->refund($refund['is_refund'])) {
            return $this->renderSuccess('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 确认收到用户付款
     */
    public function collection($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->collection()) {
            return $this->renderSuccess('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }

    /**
     * 导出订单
     */
    public function export_order()
    {
        $data = $this->postData('time');
        $star = strtotime($data['star'].' 00:00:00');
        $end = strtotime($data['end'].' 23:59:59');
        vendor("PHPExcel.PHPExcel");
        $excel = new \PHPExcel();

        $excel->setActiveSheetIndex(0);
        $sheet = $excel->getActiveSheet();
        $sheet->getDefaultStyle()->getAlignment()
            ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('A1:F1')->getFont()->setName('微软雅黑')->setSize(18)->setBold(True);
        $sheet->getStyle('A3:F3')->getFont()->setBold(True);
        $sheet->getStyle('A3:F3')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('F2F2F2');
        $sheet->setTitle('统计报表');
        $sheet->setCellValue('A1','门店统计报表');
        $sheet->mergeCells('A1:F1');
        $sheet->setCellValue('A2','统计日期：'.$data['star'].' 到 '.$data['end']);
        $sheet->mergeCells('A2:F2');
        $sheet->setCellValue('A3','序号')
            ->setCellValue('B3','门店编号')
            ->setCellValue('C3','门店名称')
            ->setCellValue('D3','收款金额')
            ->setCellValue('E3','退款金额')
            ->setCellValue('F3','到账金额');

        $model = new ShopModel;
        $shop = $model->getList();
              
        $row = 4;
        foreach($shop as $key=>$val){
            $cash = OrderModel::getCashCount($val['shop_id'],$star,$end);
            $sheet->setCellValue('A'.$row,$row-3)
            ->setCellValue('B'.$row,$val['shop_id'])
            ->setCellValue('C'.$row,$val['shop_name'])
            ->setCellValue('D'.$row,$cash['pay_price'])
            ->setCellValue('E'.$row,$cash['refund_price'])
            ->setCellValue('F'.$row,'');
            //->setCellValue('F'.$row,$cash['reach_price']);
            $row++;
        }
        $row--;
        $sheet->getStyle('A3:F'.$row)->applyFromArray([
            'borders' => [
                'allborders' => [
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,
                    'color' => [
                        'rgb' => '000000'
                    ]
                ]
            ]
        ]); 
        

        for($n=0;$n<sizeof($shop);$n++){
            $excel->createSheet();
            $excel->setActiveSheetIndex($n+1);
            $sheet = $excel->getActiveSheet();
            $sheet->getDefaultStyle()->getAlignment()
                ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)
                ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $sheet->getStyle('A1:J1')->getFont()->setName('微软雅黑')->setSize(18)->setBold(True);
            $sheet->getStyle('A3:J3')->getFont()->setBold(True);
            $sheet->getStyle('A3:J3')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('F2F2F2');
            $sheet->setTitle($shop[$n]['shop_name']);
            $model = new OrderModel;
            $list = $model->where('shop_id',$shop[$n]['shop_id'])
                    ->where('order_status' , '>',29)
                    ->where('create_time','>',$star)
                    ->where('create_time','<',$end)
                    ->order('order_id','desc')
                    ->select();//获取门店订单

            $sheet->setCellValue('A1','门店订单流水');
            $sheet->mergeCells('A1:J1');
            $sheet->setCellValue('A2','流水日期：'.$data['star'].' 到 '.$data['end']);
            $sheet->mergeCells('A2:J2');
            $sheet->setCellValue('A3','序号')
                ->setCellValue('B3','交易单号')
                ->setCellValue('C3','订单类型')
                ->setCellValue('D3','支付方式')
                ->setCellValue('E3','商品总额')
                ->setCellValue('F3','其它费用')
                ->setCellValue('G3','优惠金额')
                ->setCellValue('H3','实付金额')
                ->setCellValue('I3','退款金额')
                ->setCellValue('J3','到账金额');
            $sheet->getStyle('B')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);

            $row = 4;
            foreach($list as $key=>$val){
                //判断订单类型
                if($val['table_id']==2){
                    $order_type = '打包';
                }elseif($val['table_id']==3){
                    $order_type = '外卖';
                }else{
                    $order_type = '堂食';
                }
                //其它费用 ，配送费+打包费+餐具费
                $other_price = $val['express_price']+$val['pack_price']+$val['ware_price'];
                //计算到账金额
                if($val['order_status']['value']==40){
                    $reach_price = $val['pay_price']-$val['refund_price'];
                    $reach_price = $reach_price-round($reach_price*0.006,2);

                }else{
                   $reach_price = $val['pay_price']-round($val['pay_price']*0.006,2); 
                }
                
                $sheet->setCellValue('A'.$row,$row-3)
                ->setCellValueExplicit('B'.$row,$val['order_no'],\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('C'.$row,$order_type)
                ->setCellValue('D'.$row,empty($val['activity_price'])?'余额':'微信')
                ->setCellValue('E'.$row,$val['total_price'])
                ->setCellValue('F'.$row,$other_price?:'')
                ->setCellValue('G'.$row,$val['activity_price'])
                ->setCellValue('H'.$row,$val['pay_price'])
                ->setCellValue('I'.$row,$val['refund_price'?:''])
                ->setCellValue('J'.$row,'');
                //->setCellValue('J'.$row,$reach_price);
                $row++;
            }
            $row--;
            $sheet->getStyle('A3:J'.$row)->applyFromArray([
                'borders' => [
                    'allborders' => [
                        'style' => \PHPExcel_Style_Border::BORDER_THIN,
                        'color' => [
                            'rgb' => '000000'
                        ]
                    ]
                ]
            ]);         
        }

        $writer = \PHPExcel_IOFactory::createWriter($excel,'Excel2007');
        $file_name = str_replace('-','',$data['star']).'-'.str_replace('-','',$data['end']);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$file_name.'.xlsx"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
    }

}
